import datetime
import json

from DataRecorder.recorder import Recorder
from DrissionPage._configs.chromium_options import ChromiumOptions
from DrissionPage._pages.chromium_page import ChromiumPage

"""
监听控制台输出
获取用户的操作
"""


class Manager:
    def __init__(self):
        self.init_page()
        self.call_back()
        self.filename = datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S')
        self.filepath = f"record_list/{datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S')}.csv"
        self.recorder = Recorder(self.filepath)

    def call_back(self):
        self.page.driver.run('Console.enable')
        self.page.driver.set_callback('Console.messageAdded', self.console_message_call_back)
        self.page.run_cdp('Target.setDiscoverTargets', discover=True)
        self.page.driver.set_callback('Target.targetCreated', self.target_change_call_back)

    def target_change_call_back(self, **kwargs):
        target_info = kwargs.get('targetInfo')
        url = target_info['url']
        print(url)

    def console_message_call_back(self, **kwargs):
        kwargs = kwargs.get('message')
        source = kwargs.get('source')
        level = kwargs.get('level')
        text = kwargs.get('text')
        if source != 'console-api' and level != 'info':
            return
        if 'xpath' not in text:
            return
        print("触发了消息", kwargs)
        self.recorder.add_data([text])
        self.recorder.record()

    def init_page(self):
        co = ChromiumOptions()
        self.page = ChromiumPage(co)
        with open('click_new.js', 'r', encoding='utf-8') as file:
            js = file.read()
        self.page.add_init_js(js)
        # self.page.get("https://www.baidu.com")


class Replay:
    def __init__(self, filename):
        self.filename = filename
        self.page = ChromiumPage()
        self.url = None
        self.replay()

    def replay(self):

        import csv
        csv_reader = csv.reader(open(self.filename))
        for row in csv_reader:
            data = json.loads(row[0])
            self.controls(data)

    def controls(self, data):
        url = data['url']
        if not self.url:
            self.page.get(url)
        type_ = data['type']
        xpath = data['xpath']
        if type_ == 'click':
            self.page.ele(f"x:{xpath}").click()
        elif type_ == 'compositionend':
            self.page.ele(f"x:{xpath}").input(data['input'])


if __name__ == '__main__':
    # manager = Manager()
    # input('')
    Replay('record_list/2024-07-19_10-42-30.csv')
